package com.sg.common.empty.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sg.common.empty.service.TableBeanService;
import com.sg.common.properties.PropertyFileUtil;
import com.sg.common.utils.Constant;
import com.sg.common.utils.StrUtil;

@Repository
@Controller
public class CommonController {
	
	@Autowired
	TableBeanService tbService;
	
	@RequestMapping(value = "/flush")
	@ResponseBody
	public Object fl(HttpServletRequest request) throws IOException {
		String q = request.getParameter("_q");
		if(StrUtil.requestParamsNotEmpty(q)){
			tbService.flush(q);
		}
		return "succ";
	}

	@RequestMapping(value = "/flushConf")
	@ResponseBody
	public Object flush(HttpServletRequest request) throws IOException {
		PropertyFileUtil.flushCONF(Constant.PROPERTIES_PATH);
		return "succ";
	}
	
	@RequestMapping(value = "/download")
	@ResponseBody
	public Object dl(HttpServletRequest request, HttpServletResponse response) throws IOException {
		File file = new File(request.getParameter("_exportUrl"));
		String fileName = file.getName();
		FileInputStream excelStream = new FileInputStream(file);
		response.setHeader("Content-Disposition", "attachment;filename="
				+ fileName);
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		OutputStream output = response.getOutputStream();
		BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
		bufferedOutPut.flush();
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = excelStream.read(buffer, 0, 8192)) != -1) {
			bufferedOutPut.write(buffer, 0, bytesRead);
		}
		bufferedOutPut.close();
		return "";
	}
}
